package com.zsd.android.okhttplib;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class SocketRequestServer {

    public static final String VERSION = "HTTP/1.1";

    /**
     * todo 通过Request对象，寻找到域名HOST
     * @param request
     * @return
     */
    public String getHost(Request request) {
        try {
            URL url = new URL(request.getUrl());
            return url.getHost();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * todo 获取端口号
     * @param request
     * @return
     */
    public int getPort(Request request) {
        try {
            URL url = new URL(request.getUrl());
            int port = url.getPort();
            return port == -1 ? url.getDefaultPort() : port;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * todo 获取请求头的所有信息
     * @param request
     * @return
     */
    public String getRequestHeaderAll(Request request) {
        //得到请求方式
        URL url = null;
        try {
            url = new URL(request.getUrl());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        String file = url.getFile();
        //TODO 拼接请求头的请求行
        // GET /v3/weather/weatherInfo?city=110101&key=1341543f3252 HTTP/1.1\r\n
        StringBuffer sb = new StringBuffer();
        sb.append(request.getRequestMethod());
        sb.append(" ");
        sb.append(file);
        sb.append(" ");
        sb.append(VERSION);
        sb.append("\r\n");
        //TODO 获取请求集进行拼接
        // Content-Length: 48\r\n
        // Host: restapi.amap.com\r\n
        // Content-Type: application/x-www-form-urlencoded\r\n
        HashMap<String, String> headerList = request.getHeaderList();
        if (!headerList.isEmpty()) {
            for (Map.Entry<String, String> entry : headerList.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                sb.append(key);
                sb.append(": ");
                sb.append(value);
                sb.append("\r\n");
            }
            //拼接空行，代表下面的POST，请求体
            sb.append("\r\n");
        }
        //TODO 请求体的拼接
        if (Request.POST.equalsIgnoreCase(request.getRequestMethod())) {
            sb.append(request.getRequestBody().getBody());
            sb.append("\r\n");
        }
        return sb.toString();
    }

    /**
     * 通过url，判断是Http还是Https
     * @param requestUrl
     * @return
     */
    public String queryHttpOrHttps(String requestUrl) {
        try {
            URL url = new URL(requestUrl);
            return url.getProtocol();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
